package com.styytech.dadabao.widge.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.styytech.dadabao.R;
import com.styytech.dadabao.base.BaseActivity;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by user on 2015/8/17.
 */
public class CalculationDialog {
    private Dialog mDialog;

    private Context mContext;
    private BaseActivity baseActivity;
    private View view;
    private ImageButton ibtn_close;
    private EditText edt_insert;
    //本息相加
    private TextView tv_total_money;
    //利息共收入
    private TextView tv_get_total;
    //平均每天收入
    private TextView tv_get_month;
    //多少天
    private int date;
    //利益率
    private double proportion;
    //投资上限
    private double totalNumber;
    public CalculationDialog (Context context,BaseActivity activity,String date,String proportion,double totalNum){
        this.mContext=context;
        this.baseActivity=activity;
        this.date=Integer.parseInt(date);
        this.proportion=(Double.parseDouble(proportion))/100;
        this.totalNumber=totalNum;
        initViews();
    }

    private void initViews(){
        mDialog = new Dialog(mContext,
                R.style.seek_dialog);
        LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.dialog_income_calculation, null);
        edt_insert=(EditText)view.findViewById(R.id.edt_insert);
        edt_insert.addTextChangedListener(new NumWatcher(edt_insert));
        tv_total_money=(TextView)view.findViewById(R.id.tv_total_money);
        tv_get_total=(TextView)view.findViewById(R.id.tv_get_total);
        tv_get_month=(TextView)view.findViewById(R.id.tv_get_month);
        ibtn_close=(ImageButton)view.findViewById(R.id.ibtn_close);
        ibtn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        setView();

    }

    /**
     * 设置点击屏幕或者back返回键能否取消*/
    public void NotCancel(boolean cancel){
        mDialog.setCanceledOnTouchOutside(cancel);//false设置点击屏幕其他地方，dialog不消失
        mDialog.setCancelable(cancel);//false设置点击返回键和HOme键，dialog不消失
    }
    public void show(){
        mDialog.show();
    }

    public void dismiss(){
        mDialog.dismiss();
    }



    private void setView(){
        NotCancel(false);
        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                baseActivity.hideSoftInput();
            }
        });
       // mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        mDialog.setContentView(view);
        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager m = ((Activity)mContext).getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
         p.height = (int) (d.getHeight() * 0.4); // 高度设置为屏幕的0.6
        p.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.65
        dialogWindow.setAttributes(lp);

    }

    class NumWatcher implements TextWatcher {

        // 监听改变的文本框
        private EditText editText;
        private int editStart;
        private int editEnd;
        // 本+息
        double profit_total_all;
        String num_total_all;
        // 息
        double profit_toatl;
        String num_total;
        // 每天息
        double profit_day;
        String num_day;

        /**
         * 构造函数
         */
        public NumWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void onTextChanged(CharSequence ss, int start, int before,
                                  int count) {
            String editable = editText.getText().toString();
            String str = stringFilter(editable.toString());
            if (!editable.equals(str)) {
                editText.setText(str);
                // 设置新的光标所在位置 www.2cto.com editText.setSelection(str.length());
                Toast.makeText(mContext.getApplicationContext(), "输入字符无意义!",
                        Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            editStart = edt_insert.getSelectionStart();
            editEnd = edt_insert.getSelectionEnd();
            if (!edt_insert.getText().toString().equals("")) {
                if (Double.parseDouble(edt_insert.getText().toString()) > (double)1000000.00) {

                    Toast.makeText(mContext.getApplicationContext(), "最大金额100w！",
                            Toast.LENGTH_SHORT).show();
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    edt_insert.setText(s);
                    edt_insert.setSelection(tempSelection);
                } else {
                    // 投资金额
                    double money_num = Double.parseDouble(edt_insert.getText()
                            .toString());
                    //每天的利息
                    profit_day=(double)((money_num*proportion)/360);
                   // num_day = String.format("%.2f", profit_day);
                    num_day= formatTosepara((float) profit_day*30);
                    setText(tv_get_month,num_day);

                    //利息共收入
                    profit_toatl=profit_day*date;
                    //num_total = String.format("%.2f", profit_toatl);
                    num_total= formatTosepara((float) profit_toatl);
                    setText(tv_get_total,num_total);
                    //本+息
                    profit_total_all=money_num+profit_toatl;
                    //num_total_all=String.format("%.2f", profit_total_all);
                    num_total_all= formatTosepara((float) profit_total_all);
                    setText(tv_total_money,num_total_all);
                }
            }else{
                tv_total_money.setText(0+"");
                tv_get_total.setText(0+"");
                tv_get_month.setText(0+"");
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

    }
    public static String formatTosepara(float data) {
        DecimalFormat df = new DecimalFormat("##,##0.00");
        return df.format(data);
    }
    private void setText(TextView text,String string){
        Log.e("dasd","-----------"+string);
       String strings=subZeroAndDot(string);
        Log.e("dasd", "-----------" + strings);
        text.setText(strings);

    }
    //去掉小数点后多余的0
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "^[^[1-9]]\\d*";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }



}
